package com.example.test_demo.async.another;

import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * 计算结果
 *
 * @author Lixiaobing on 2020/04/17
 */
@Data
public class Result {
    private Boolean success = true;
    private Integer code;
    private String msg;
    private Map<Object, Object> data = new HashMap<>();

    private Result() {
    }

    public static Result ok() {
        return new Result()
                .setSucess(ResultCodeEnum.SUCCESS.getSuccess())
                .code(ResultCodeEnum.SUCCESS.getCode())
                .message(ResultCodeEnum.SUCCESS.getMessage());
    }

    public static Result ok(String msg) {
        return new Result()
                .setSucess(ResultCodeEnum.SUCCESS.getSuccess())
                .code(ResultCodeEnum.SUCCESS.getCode())
                .message(msg);
    }

    public static Result failed(String msg) {
        return new Result()
                .setSucess(ResultCodeEnum.UNKNOWN_ERROR.getSuccess())
                .code(ResultCodeEnum.UNKNOWN_ERROR.getCode())
                .message(msg);
    }

    public boolean isSuccess() {
        return success;
    }

    public Result setSucess(boolean success) {
        this.success = success;
        return this;
    }

    public String getMsg() {
        return msg;
    }

    public Result message(String msg) {
        this.msg = msg;
        return this;
    }

    public Result data(Map<Object, Object> map) {
        this.setData(map);
        return this;
    }

    public Result setV(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public Object getV(Object key) {
        return data.get(key);
    }

    public Integer getCode() {
        return code;
    }

    public Result code(Integer code) {
        this.code = code;
        return this;
    }

    @Override
    public String toString() {
        return "{" + "success=" + isSuccess() + ", code=" + getCode() + ", message=" + getMsg() + getExtData() + '}';
    }

    private String getExtData() {
        StringBuilder sb = new StringBuilder();
        data.entrySet().parallelStream().forEach(r -> {
            sb.append(", ").append(r.getKey()).append("=").append(r.getValue());
        });
        return sb.toString();
    }
}

